package com.raysdata.smartcity.tools;

import com.raysdata.smartcity.dao.RzBaseDao;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class DtoGenerator {
    public static void go(RzBaseDao dao, String path, String table){
        String fileName = GeneratorUtil.toUpperCaseFirstOne(table.replace("yp_",""));
        VelocityEngine ve = new VelocityEngine();
        ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        ve.init();
        Template dtoTpl = ve.getTemplate("com/raysdata/smartcity/tools/dtoTpl.vm");
        VelocityContext ctx = new VelocityContext();
        if(path!=null&&!path.equals("")){
            ctx.put("package","package com.raysdata.smartcity.dto."+path+";");
        }else{
            ctx.put("package","package com.raysdata.smartcity.dto;");
        }
        ctx.put("dtoFileName",fileName);
        ctx.put("props", getDtoDatas(dao,table));
        GeneratorUtil.merge(dtoTpl, ctx, GeneratorUtil.getPath("dto") +path+"/"+ fileName + ".java");
    }

    private static List<Map<String,String>> getDtoDatas(RzBaseDao dao, String table){
        List<String> cols = dao.getTableColumns(table);
        List<Integer> colTypes = dao.getTableColumnTypes(table);
        List<Map<String,String>> list = new ArrayList<>();
        for(int i=0;i<cols.size();i++){
            Map<String,String> map = new HashMap<>();
            map.put("pType",GeneratorUtil.getTypeByCode(colTypes.get(i)));
            map.put("pName",cols.get(i));
            map.put("PName", GeneratorUtil.toUpperCaseFirst(cols.get(i)));
            list.add(map);
        }
        return list;
    }
}
